package com.cf.common.mvp;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.cf.common.rx.LifecycleRegistryToBehaviorSubject;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * @author yangji
 */
public abstract class BasePresenter<V extends BaseView> extends LifecycleRegistryToBehaviorSubject {

    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    private WeakReference<V> mvpView;

    private V presenterView = null;

    void bindView(@NonNull V v) {
        mvpView = new WeakReference<>(v);
    }

    @Nullable
    protected V getMvpView() {
        return mvpView == null ? null : mvpView.get();
    }

    @NonNull
    protected V getPresenterView() {
        if (presenterView == null) {
            presenterView = createPresenterView();
        }
        return presenterView;
    }

    @NonNull
    protected abstract V createPresenterView();

    protected void addDisposable(Disposable d) {
        mCompositeDisposable.add(d);
    }

    protected <T> LifecycleTransformer<T> bindUntilEvent() {
        return RxLifecycle.bindUntilEvent(getSubject(), ActivityEvent.DESTROY);
    }

    private <T> LifecycleTransformer<T> bindUntilEvent(ActivityEvent event) {
        return RxLifecycle.bindUntilEvent(getSubject(), event);
    }


    private void unBindView() {
        mCompositeDisposable.dispose();
        mCompositeDisposable.clear();
        mCompositeDisposable = null;
        mvpView.clear();
        mvpView = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unBindView();
    }

    void test() {
        Observable.timer(1, TimeUnit.SECONDS)
                .compose(bindUntilEvent(ActivityEvent.STOP))
                .doOnSubscribe(disposable -> {

                })
                .subscribe();
    }

}
